package com.xx566.blog.controller;

import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.ehcache.CacheKit;
import com.xx566.blog.bean.CacheBean;
import com.xx566.blog.common.XX566Cache;
import com.xx566.blog.common.XX566Cache.CacheKey;
import com.xx566.blog.common.XX566Utils;
import com.xx566.blog.model.Article;
import com.xx566.blog.model.Friendly;
import com.xx566.blog.model.Message;
import com.xx566.blog.model.Tags;
import com.xx566.blog.utils.LuceneUtil;
import com.xx566.blog.utils.MD5Util;
import com.xx566.blog.utils.PageUtil;
import org.apache.log4j.Logger;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

public class XX566Controller extends Controller {

    private static final Logger LOGGER = Logger
            .getLogger(XX566Controller.class);

    private Map<String, String> ipMap = new HashMap<String, String>() {

        private static final long serialVersionUID = 1L;

        {
            put("127.0.0.1", "127.0.0.1");
        }
    };

    /**
     * 跳转到首页
     *
     * @Title: index
     * @author Realfighter
     * @date 2014-6-3 上午11:16:12 void
     */
    public void index() {
        this.setAllCache();
        int pagenum = 1;
        int pageSize = Integer.parseInt(XX566Utils.getProperty("reshits"));
        long tagid = 0;// 标签ID
        String time = "0-0";// 归档日期
        String searchKey = "";// 搜索关键字
        if (!isParaBlank(0)) {// 页码
            pagenum = getParaToInt(0);
        }
        if (!isParaBlank(1)) {// 标签ID
            tagid = getParaToInt(1);
        }
        if (!isParaBlank(2) && !isParaBlank(3)) {// 归档日期
            time = getPara(2) + "-" + getPara(3);
        }
        if (!isParaBlank(4)) {// 关键字
            try {
                searchKey = URLDecoder.decode(URLDecoder.decode(getPara(4),
                        "UTF-8"), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                // 解码错误不处理
                searchKey = "";
            }
        }
        Page<Article> page = null;
        if (!"".equals(searchKey)) {
            // lucene检索
            String aids = LuceneUtil.searchString(searchKey);
            page = Article.dao.findArticle4PageByKey(pagenum, pageSize,
                    searchKey, aids);
        } else {
            page = Article.dao.findArticles4Page(pagenum, pageSize, tagid,
                    time, 0, false);
        }
        setAttr("search_key", searchKey);
        setAttr("index_tagid", tagid);
        setAttr("index_time", time);
        setAttr("page", new PageUtil(page));
        render("index.jsp");
    }

    /**
     * 文章详情
     */
    @SuppressWarnings("unchecked")
    public void detail() {
        String ip = XX566Utils.getIpAddrByRequest(getRequest());
        int type = getParaToInt(0);// 文章ID
        setAttr("articletag", type);
        if (type != XX566Utils.ARCHIVE && type != XX566Utils.CATES) {// 归档信息和分类不需要记录
            Article art = Article.dao.findById(type);
            if (!ipMap.containsKey(ip)) {
                int count = art.getInt("clicks");
                count++;
                art.set("clicks", count);
                art.update();// 阅读数
            }
        }
        boolean flag = true;
        switch (type) {
            case XX566Utils.ARCHIVE:// 归档信息
                flag = false;
                List<Article> archives = Article.dao.findArchives();
                setAttr("archives", archives);
                break;
            case XX566Utils.CATES:// category分类
                flag = false;
                String category = null;
                try {
                    category = URLDecoder.decode(URLDecoder.decode(getPara(2),
                            "UTF-8"), "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    LOGGER.error("中文转码异常：" + e);
                }
                List<Tags> tags = Tags.dao.findByCategory(category);
                setAttr("cate_para", getPara(2));
                setAttr("cate_tags", category);
                setAttr("catetags", tags);
                break;
        }
        if (flag) {// 文章、留言、关于都需要详情展示
            Article article = Article.dao.findArticleInfoById(type);
            setAttr("article", article);
            List<Article> articles = Article.dao.findArticlePrevAndNextById(type);
            setAttr("article2", articles);
        }
        int pageNum = 1;
        if (isParaExists(1)) {
            pageNum = getParaToInt(1);
        }
        Page<Message> msgPage = (Page<Message>) Message.dao.findMsg4Page(
                pageNum, 10, 0, type, true, true);
        setAttr("msgPage", new PageUtil(msgPage));
        Map<String, List<Message>> msgMap = new HashMap<String, List<Message>>();
        for (Message msg : msgPage.getList()) {
            List<Message> msgList = (List<Message>) Message.dao.findMsg4Page(
                    null, null, msg.getInt("id"), type, false, false);
            msgMap.put(msg.getInt("id").toString(), msgList);
        }
        setAttr("msgMap", msgMap);
        this.setAllCache();
        render("detail.jsp");
    }

    /**
     * 友情链接
     *
     * @Title: click
     * @author Realfighter
     * @date 2014-6-7 下午02:04:49 void
     */
    public void click() {
        String ip = XX566Utils.getIpAddrByRequest(getRequest());
        int id = getParaToInt();
        Friendly friendly = Friendly.dao.findById(id);
        if (!ipMap.containsKey(ip)) {
            int count = friendly.getInt("counts");
            count++;
            friendly.set("counts", count);
            if (friendly.update()) {
                redirect(friendly.getStr("url"));
            }
        } else {
            redirect(friendly.getStr("url"));
        }
    }

    /**
     * 保存留言信息
     */
    public void save() {
        String returnUrl = getPara("returnUrl");
        setAttr("returnUrl", returnUrl);
        boolean succeed = Db.tx(new IAtom() {
            @Override
            public boolean run() throws SQLException {
                Object userSessionID = getSessionAttr("xx566_userid");
                int userid = 0;
                try {
                    userid = (Integer) userSessionID;
                } catch (Exception e) {
                    userid = 0;
                }
                com.xx566.blog.model.User user;
                if (userid == 0) {
                    user = getModel(com.xx566.blog.model.User.class);
                    String username = user.getStr("name");
                    String useremail = user.getStr("email");
                    if (username != null && useremail != null) {
                        Random r = new Random();
                        int num = r.nextInt(31) + 1;// 1-31的整数
                        user.set("pwd", MD5Util.md5(useremail));
                        user.set("avatar", "image/" + num + ".jpg");
                        user.set("userip", XX566Utils
                                .getIpAddrByRequest(getRequest()));
                        com.xx566.blog.model.User user2 = com.xx566.blog.model.User.dao.findIsNameUsed(username);
                        if (user2.getLong("hasuser") == 0) {
                            user.save();
                            setSessionAttr("xx566_userid", user.getInt("id"));
                        } else {
                            setAttr("error_info", "用户名已被占用<br>您可以登录或更换用户名");
                            return false;
                        }
                    } else {
                        setAttr("error_info", "用户名必须填写<br>电子邮箱地址必须填写");
                        return false;
                    }
                } else {
                    user = com.xx566.blog.model.User.dao.findById(userid);
                }
                if (!isParaBlank("message.content")) {
                    getModel(Message.class).set("userid", user.getInt("id"))
                            .save();
                    // 更新缓存
                    CacheKit.put(CacheBean.MESSAGES, CacheBean.MESSAGES,
                            Message.dao.findMessages4Page(1, 10));
                }
                return true;
            }
        });
        if (!succeed) {
            render("error.jsp");
        } else if (isParaBlank("returnUrl")) {
            int artid = getParaToInt("message.articleid");
            redirect("/detail/" + (artid < 0 ? ("n" + artid * (-1)) : artid)
                    + ".html");
        } else {
            redirect(returnUrl);
        }
    }

    /**
     * 设置需要缓存的信息
     */
    private void setAllCache() {
        this.setFriendlysCache();
        this.setTagsCache();
        this.setArchiveTimesCache();
        this.setArticlesCache();
        this.setMessagesCache();
        this.setCatesCache();
    }

    /**
     * 设置标签分类
     */
    private void setCatesCache() {
        List<Tags> cateList = CacheKit.get(CacheBean.CATES, CacheBean.CATES,
                XX566Cache.getIDataLoaderByKey(CacheKey.cates));
        setAttr("tags_cateList", cateList);
    }

    /**
     * 友情链接
     *
     * @Title: setFriendlysCache
     * @author Realfighter
     * @date 2014-6-17 下午01:29:17 void
     */
    private void setFriendlysCache() {
        List<Friendly> friendlys = CacheKit.get(CacheBean.FRIENDLYS,
                CacheBean.FRIENDLYS, XX566Cache
                        .getIDataLoaderByKey(CacheKey.friendlys));
        setAttr("friendlys", friendlys);
    }

    /**
     * 分类标签
     *
     * @Title: setTagsCache
     * @author Realfighter
     * @date 2014-6-17 下午01:29:27 void
     */
    private void setTagsCache() {
        List<Tags> tags = CacheKit.get(CacheBean.TAGS, CacheBean.TAGS,
                XX566Cache.getIDataLoaderByKey(CacheKey.tags));
        setAttr("tags", tags);
    }

    /**
     * 归档日期
     *
     * @Title: setArchiveTimesCache
     * @author Realfighter
     * @date 2014-6-17 下午01:29:35 void
     */
    private void setArchiveTimesCache() {
        List<Article> archive_times = CacheKit.get(CacheBean.ARCHIVE_TIMES,
                CacheBean.ARCHIVE_TIMES, XX566Cache
                        .getIDataLoaderByKey(CacheKey.archives));
        setAttr("archive_times", archive_times);
    }

    /**
     * 文章
     *
     * @Title: setArticlesCache
     * @author Realfighter
     * @date 2014-6-17 下午01:30:22 void
     */
    private void setArticlesCache() {
        Page<Article> articles = CacheKit.get(CacheBean.ARTICLES,
                CacheBean.ARTICLES, XX566Cache
                        .getIDataLoaderByKey(CacheKey.articles));
        setAttr("articles", articles);
    }

    /**
     * 留言
     *
     * @Title: setMessagesCache
     * @author Realfighter
     * @date 2014-6-17 下午01:30:35 void
     */
    private void setMessagesCache() {
        Page<Message> messages = CacheKit.get(CacheBean.MESSAGES,
                CacheBean.MESSAGES, XX566Cache
                        .getIDataLoaderByKey(CacheKey.messages));
        setAttr("messages", messages);
    }

}
